// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const { productId } = event
  
  if (!productId) {
    return {
      success: false,
      errMsg: '缺少商品ID'
    }
  }
  
  try {
    // 查询商品基本信息
    const productResult = await db.collection('products').doc(productId).get()
    const product = productResult.data
    
    if (!product) {
      return {
        success: false,
        errMsg: '商品不存在'
      }
    }
    
    // 查询商品规格组
    const specGroupsResult = await db.collection('specGroups')
      .where({
        productId: productId
      })
      .orderBy('order', 'asc')
      .get()
    
    const specGroups = specGroupsResult.data
    
    // 查询规格选项
    const groupIds = specGroups.map(group => group._id)
    const specsResult = await db.collection('specs')
      .where({
        groupId: db.command.in(groupIds)
      })
      .orderBy('order', 'asc')
      .get()
    
    const specs = specsResult.data
    
    // 组装完整规格数据
    const specData = {
      product: {
        _id: product._id,
        name: product.name,
        image: product.image,
        price: product.price
      },
      specGroups: specGroups.map(group => ({
        ...group,
        specs: specs.filter(spec => spec.groupId === group._id)
      }))
    }
    
    return {
      success: true,
      data: specData
    }
  } catch (err) {
    console.error('获取套餐商品规格失败', err)
    return {
      success: false,
      errMsg: '获取套餐商品规格失败'
    }
  }
}